/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import { Form, Input, Radio, Select, InputNumber, Button, TimePicker, message  } from 'antd';
import request from '@/utils/request';
// import rtu_proto from './../../rtu_proto.js'
import { connect } from 'dva';
import styles from '../../layouts/password.less';
import moment from 'moment'
const FormItem = Form.Item;
const { TextArea } = Input;
let uuid = 2;
const RadioGroup = Radio.Group;
const Option = Select.Option;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meterArr: [1, 2],
      meterActiveKey: ['1', '2'],
      meter1: [],
      meter2: [],
      all_roles:[],
      level:0,
      mode:0
    };
  }
  base64ToHex=(str)=> {
    const raw = atob(str);
    let result = '';
    for (let i = 0; i < raw.length; i++) {
      const hex = raw.charCodeAt(i).toString(16);
      result += (hex.length === 2 ? hex : '0' + hex);
    }
    return result.toUpperCase();
  }
  componentDidMount() {
    const that=this
    if(this.props.editRecord.hardware_configs.protobuf_control){
      const range_max=this.props.editRecord.hardware_configs.customize.range_max;
      console.log(this.props.editRecord.hardware_configs.protobuf_control)
      const string0=this.props.editRecord.hardware_configs.protobuf_control.string[0]
      const buffer = Buffer.from(string0, 'hex');
      let result=rtu_proto.AMWARE.RTU03.DOWNSTREAM.decode(buffer)
      console.log(result)
      that.props.form.setFieldsValue({
        "notify":result.control.notify
      })
      if(result.control.mode){
        this.setState({
          mode:result.control.mode
        },function (){

          if(this.state.mode===1){
            that.props.form.setFieldsValue({
              "target_pressure":  Number(((( result.control.immediately.target - 4000) * range_max) / 16000).toFixed(3))
            })
          }else if(this.state.mode===2){
            let times=result.control.fixedTime.times
            uuid=times.length
            this.setState({
              meterArr:times.map((item,index)=>{
                return index+1
              }),
              meterActiveKey:times.map((item,index)=>{
                return (index+1).toString()
              }),
            })
            for(let i=0;i<times.length;i++){
              this.setState({
                [`meter${i+1}`]:[]
              },function() {
                that.props.form.setFieldsValue({
                  [`time-${i+1}`]:moment(times[i].time*1000),
                  [`pressure-${i+1}`]: Number(((( times[i].target - 4000) * range_max) / 16000).toFixed(3)),
                })
              })
            }
          }
        })
      }
    }
  }
  addMeter = () => {
    uuid++;
    this.state.meterArr.push(uuid);
    this.state.meterActiveKey.push(uuid.toString());
    this.setState({
      [`meter${uuid}`]: [],
      meterArr: this.state.meterArr,
      meterActiveKey: this.state.meterActiveKey,
    });
  };
  deleteMeter = (item) => {
    console.log('删除的item', item);
    if (this.state.meterArr.length === 2) {
      console.log('只有一个水表');
      message.error('分时至少需要2个时间')
      return false
    }
    const index = this.state.meterArr.indexOf(item);
    console.log('index', index);
    this.state.meterArr.splice(index, 1);
    this.setState({
      meterArr: this.state.meterArr,
    });
  };
  render() {
    const range = this.props.editRecord.hardware_configs.protobuf_json ?
      this.props.editRecord.hardware_configs.protobuf_json.rtu03.sensor_cfg.range / 1000 : '';
    console.log('range',range)
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      }
    };
    const range_max = this.props.editRecord.hardware_configs.protobuf_json ?
      this.props.editRecord.hardware_configs.protobuf_json.rtu03.sensor_cfg.range / 1000 : '';
    console.log('range_max',range_max)
    const {getFieldDecorator} = this.props.form;
    const control_valve=this.props.hardware_configs.control_valve;
    console.log('control_valve')
    const config_index=0;
    const that=this
    const meterForms = this.state.meterArr.map((item, index) => {
      return (
        <Form style={{ display: 'flex' }} className={'custom-table-form'} key={index} layout="inline">
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`time-${item}`, {
            })(
              <TimePicker  style={{  fontWeight: 'bold' ,width:'100%'}}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`pressure-${item}`, {
              initialValue: '',
            })(
              <InputNumber onChange={(e)=>{
                if(that.props.form.getFieldValue(`method`)==='1'){
                  let result=Number((Number(e)+Number(e)*0.1).toFixed(2))
                  that.props.form.setFieldsValue({
                    [`upper_limit-${item}`]:(result>range)?range:result
                  })
                }

              }} max={that.props.form.getFieldValue(`method`)==='1'?range:Infinity}  step={that.props.form.getFieldValue(`method`)==='1'?0.01:1} style={{  fontWeight: 'bold',width:'100%' }} />,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`upper_limit-${item}`, {
              initialValue: '',
            })(
              <InputNumber   max={that.props.form.getFieldValue(`method`)==='1'?range:Infinity}  step={that.props.form.getFieldValue(`method`)==='1'?0.01:1} style={{  fontWeight: 'bold',width:'100%' }} />,
            )}
          </FormItem>
          <div style={{ width: '80px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            <Button
              style={{ height: '22px' }}
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                e.stopPropagation();
                this.deleteMeter(item);
              }
              }
            >删除
            </Button>
          </div>


        </Form>
      );
    });

    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
      {/*     <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
                满量程(MPa)
            </span>
            )}
          >
            {getFieldDecorator('range_max', {
              initialValue: range_max
            })(
              <InputNumber  disabled={true} style={{width:'100%'}}/>
            )}
          </FormItem> */}
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              模式
            </span>
            )}>
            {getFieldDecorator('mode', {
              initialValue: this.state.mode,
            })(
              <Select  onChange={(e)=>{
                this.setState({
                  mode:Number(e),
                })
              }}>
                { [{name:'停止控制',id:0},{name:'立即控制',id:1},{name:'定时控制',id:2}].map((item, key) => {
                  return (
                    <Option  key={item.id}  value={item.id}>{item.name}</Option>
                  )
                }) }
              </Select>
            )}
          </FormItem>
          {
            this.state.mode===1&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
                控制方法
            </span>
              )}
            >
              {getFieldDecorator('method', {
                initialValue:this.state.method
              })(
                <Select onChange={(e)=>{
                  this.setState({
                    method:e
                  })
                }}>
                  <Option value={"0"}>手动控制</Option>
                  <Option value={'1'}>自动控制</Option>
                </Select>
              )}
            </FormItem>
          }
          {
            this.state.mode===1&&this.state.method==='0'&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
                {this.state.method==='0'?'目标位置':'目标压力(MPa)'}
            </span>
              )}
            >
              {getFieldDecorator('target_pressure', {
                initialValue:""
              })(
                <InputNumber   step={1}  style={{width:'100%'}}/>
              )}
            </FormItem>
          }
          {
            this.state.mode===1&&this.state.method==='1'&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
                {'目标压力(MPa)'}
            </span>
              )}
            >
              {getFieldDecorator('target_pressure', {
                initialValue:""
              })(
                <InputNumber onChange={(e)=>{
                  let result=Number((Number(e)+Number(e)*0.1).toFixed(2))
                  that.props.form.setFieldsValue({
                    "upper_limit":(result>range_max)?range_max:result
                  })
                }} min={0}  step={0.01}  style={{width:'100%'}} max={range_max}/>
              )}
            </FormItem>
          }
          {
            this.state.mode===1&&this.state.method==="1"&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
                压力上限(MPa)
            </span>
              )}
            >
              {getFieldDecorator('upper_limit', {
                initialValue:0
              })(
                <InputNumber min={0}  step={this.state.method==='0'?1:0.01}  style={{width:'100%'}} max={this.state.method==='0'?Infinity:range_max}/>
              )}
            </FormItem>
          }

          {
            this.state.mode===2&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
                控制方法
            </span>
              )}
            >
              {getFieldDecorator('method', {
                initialValue:this.state.method
              })(
                <Select onChange={(e)=>{
                  this.setState({
                    method:e
                  })
                }}>
                  <Option value={"0"}>手动控制</Option>
                  <Option value={'1'}>自动控制</Option>
                </Select>
              )}
            </FormItem>
          }
          {
            this.state.mode===2&&this.state.method&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
                分时调压
            </span>
              )}
            >
              <div style={{ border: '1px solid #d9d9d9', marginTop: '10px' }}>

                <div style={{
                  display: 'flex',
                  fontWeight: 'bold',
                  lineHeight: '32px',
                  height: '32px',
                  background: 'rgb(249,249,249)',
                }}>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>时间</div>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9', }}>{
                    that.props.form.getFieldValue(`method`)==='1'?'目标压力(MPa)':'目标位置'
                  }</div>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9', }}>{
                    that.props.form.getFieldValue(`method`)==='1'?'目标上限(MPa)':'目标上限'
                  }</div>
                  <div style={{ width: '80px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>操作</div>
                </div>
                {meterForms}


              </div>
              <Button type={'primary'} className={'btn-cyan'} icon={'plus'} block onClick={this.addMeter}>添加时间</Button>
            </FormItem>
          }


        </Form>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


